<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/03/22
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\user;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use Imi\Config;
use Imi\Cache\CacheManager as Cache;


/**
 * 大转盘抽奖🧿
 * @Auth(name="token",nologin={"get_prize_list"})
 * @Controller("/user.prize/")
 */
class Prize extends UserBean
{
    protected $noNeedLogin = ['get_prize_list'];
    protected $noNeedRight = ['*'];




    /**
     * 获取奖品列表🧿
     *
     * @return void
     * @Action
     */
    public function get_prize_list()
    {


        $data['switch'] = 1;

        $list = Db::name('prize')->whereEx($data)->select()->getArray();



        if ($list)
            foreach ($list as $key => &$val) {
                $this->ChangeFieldData($val);
            }
        return $this->success('ok', $list);
    }

    /**
     * 积分购买抽奖
     *
     * @return void
     * @Action
     */
    public function buy_prize()
    {
        $score = config('prize_need_score');
        //判断积分是否充足
        if ($this->auth->user()->score < $score)
            return $this->error('积分不足');
        // 扣掉积分
        $this->DecUserScore($this->auth->user()->id, $score, '大转盘抽奖支付积分', 3);

        // 随机抽奖
        $prize_id = $this->RandPrize();


        // 是否中奖,中奖添加记录发发放奖品
        if ($prize_id) {
            //发奖品
            $prize = Db::name('prize')->where('id', '=', $prize_id)->select()->get();
            $data['type_status'] = $prize['type_status'];

            //奖品类型:1=积分,2=贝壳,3=优惠券,4=体验卡
            switch ($data['type_status']) {
                case '1':
                    $data['value'] = $prize['value'];
                    $this->IncUserScore($this->auth->user()->id, $data['value'], '大转盘中奖得积分', 4);
                    break;
                case '2':
                    $data['value'] = $prize['value'];

                    break;
                case '3':
                    $data['coupon_id'] = $prize['coupon_id'];

                    break;
                case '4':
                    $data['experience_id'] = $prize['experience_id'];

                    break;
                default:
                    # code...
                    break;
            }
            $msg = '恭喜您!抽中' . $prize['name'];
            $data['prize_id'] = $prize_id;
            $data['status'] = '2'; //状态:1=未中奖,2=中奖
        } else {
            $msg = '谢谢惠顾';
            $data['status'] = '1'; //状态:1=未中奖,2=中奖
        }
        $data['score'] = $score;
        $data['user_id'] = $this->auth->user()->id;
        $data['createtime'] = time();
        Db::name('prize_log')->insert($data)->getLastInsertId();

        return $this->success($msg);
    }

    /**
     * 抽奖
     *
     * @return void
     */
    protected function RandPrize()
    {
        $data['switch'] = 1;
        $list = Db::name('prize')->whereEx($data)
            // ->cache(\Imi\Config::get('site.db_cache_set') ?? 10)
            ->select()->getArray();
        $name_md5 = 'prize_' . md5(json_encode($list));
        $prize_arr = Cache::get('redis', $name_md5);
        if (!$prize_arr) {


            $z = 0; //总中奖次数
            $thank_ratio = 100 - Db::name('prize')->whereEx($data)
                // ->cache(\Imi\Config::get('site.db_cache_set') ?? 10)
                ->sum('ratio');
            if ($thank_ratio < 0)
                return $this->error('几率设置错误');
            $prize_arr = [];
            foreach ($list as $key => $v) {
                $t = $v['ratio'] * 100;
                // $z = $t+$z;
                for ($i = 0; $i < $t; $i++) {
                    $prize_arr[] = $v['id'];
                }
            }
            $t = $thank_ratio * 100;
            // $z = $t+$z;
            for ($i = 0; $i < $t; $i++) {
                $prize_arr[] = 0;
            }


            Cache::set('redis', $name_md5, $prize_arr, 3600);
        }

        //取到中奖数组

        $prize_id = $prize_arr[array_rand($prize_arr, 1)]; //取随机

        // //⌚️2023-3-31 10:56 加入卡片有数量限制，如果没有了就没抽中
        // $prize = Db::name('prize')->where('id', $prize_id)->select()->get();
        // if ($prize['stock'] <= $prize['num']) {
        //     return null;
        // }


        if ($prize_id > 1) {
            return $prize_id;
        } else {
            return null;
        }
    }

    /**
     * 获取中奖日志列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $status 状态:1=未中奖,2=中奖
     * @return void
     * @Action
     */
    public function get_prize_log_list(?int $page = 1, ?int $limit = 10, $date = null, $status = null)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;

        $data['user_id'] = $this->auth->user()->id;
        if ($status)
            $data['status'] = $status; //状态:1=未中奖,2=中奖

        $list = Db::name('prize_log')->whereEx($data)->page($page, $limit)->orderRaw('createtime desc')->select()->getArray();
        // if ($list)
        // foreach ($list as $key => &$val) {
        //     // $this->ChangeFieldData($val);
        // }
        return $this->success('ok', $list);
    }





    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldData(&$val)
    {
        // $val['date_str'] = $this->TimeToStr($val['createtime']);
        // $val['date'] = date('Y-m-d H:i:s', $val['createtime']);

        return $val;
    }
}
